from threading import Thread
from datetime import datetime
from src.common import MessageQueue
from src.common.logger import getLogger
from src.modules.home.service import user_service
from src.modules.memory.service import HistoryRecordService, MemoryDetailService

logger = getLogger()

class ScheduleMessage:

    def __init__(self):
        logger.info("ScheduleMessage __init__")
        self.count = 0

    def message_user_count(self):
        user_count, visit_count = 0, 0

        user_list = user_service.load_user_list()
        for user in user_list:
            user_count += 1
            visit_count += user["visit"]

        user_statistics = { "user_count": user_count, "visit_count": visit_count }
        MessageQueue.send_message_queue(user_statistics)
        return user_statistics

    def message_dialog_response(self):
        history_dict = {}
        history_records = HistoryRecordService.load_history_records({})
        for record in history_records:
            key = record["source"] + ("-" if record["pattern"] else "")
            key = key + (record["pattern"] if record["pattern"] else "")
            values = history_dict.get(key)
            if values:
                values.append(record["id"])
            else:
                history_dict[key] = [ record["id"] ]
        logger.info(f"ScheduleMessage message_dialog_response history_records: {history_dict}")

        memory_dict, detail_dict = {}, {}
        date_format = "%Y-%m-%d %H:%M:%S"
        memory_details = MemoryDetailService.load_memory_details({})
        memory_details = sorted(memory_details, key = lambda x: (x["source_id"], x["create_time"]))
        for detail in memory_details:
            key = detail["source_id"]
            if "user" == detail["type"]:
                number = memory_dict[key]["number"] if key in memory_dict and "number" in memory_dict[key] else 0
                time = memory_dict[key]["time"] if key in memory_dict and "time" in memory_dict[key] else 0
                memory_dict[key] = { "number": (number + 1), "time": time }
                detail_dict[key] = detail
            elif "ai" == detail["type"]:
                user_record = detail_dict[key]
                if user_record and "user" == user_record["type"]:
                    start = datetime.strptime(user_record["create_time"], date_format)
                    end = datetime.strptime(detail["create_time"], date_format)
                    number = memory_dict[key]["number"] if key in memory_dict and "number" in memory_dict[key] else 0
                    memory_dict[key] = { "number": number, "time": (end - start).total_seconds() }
                else:
                    memory_dict[key]["time"] = 0

        history_memory_statistics = { "history_records": history_dict, "memory_details": memory_dict }
        logger.info(f"ScheduleMessage message_dialog_response memory_details: {memory_dict}")
        MessageQueue.send_message_queue(history_memory_statistics)
        return history_memory_statistics

    def send_schedule_message(self):
        from src import app

        count = self.count
        with app.app_context():
            logger.info(f"ScheduleMessage send_schedule_message count: {count}")
            count += 1
            self.count = count

            self.message_user_count()
            self.message_dialog_response()

    def init_schedule_message(self):
        schedule_thread = Thread(target = self.send_schedule_message, daemon = True)
        schedule_thread.start()
